package com.banksoft.cps.service.impl;

import com.banksoft.cps.bean.SupplierCompany;
import com.banksoft.cps.bean.query.SupplierCompanyQuery;
import com.banksoft.cps.bean.warpper.SupplierCompanyWarpper;
import com.banksoft.cps.dao.FileInfoDao;
import com.banksoft.cps.dao.SupplierCompanyDao;
import com.banksoft.cps.service.SupplierCompanyService;
import com.banksoft.cps.util.UUIDFactory;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * Created by rongzhao.zhu on 2018/1/12.
 */
@Service
public class SupplierCompanyServiceImpl implements SupplierCompanyService {

    @Autowired
    SupplierCompanyDao supplierCompanyDao;
    @Autowired
    FileInfoDao fileInfoDao;
    
    @Override
    public List<SupplierCompany> list(SupplierCompanyQuery query) {
        return supplierCompanyDao.list(query);
    }

    @Override
    public long count(SupplierCompanyQuery query) {
        return supplierCompanyDao.count(query);
    }

    @Override
    public void save(SupplierCompany bean) {
        if(StringUtils.isNotBlank(bean.getId())){
            supplierCompanyDao.update(bean);
        }else {
            bean.setId(UUIDFactory.random());
            bean.setCreateTime(System.currentTimeMillis());
            supplierCompanyDao.insert(bean);
        }
    }

    @Override
    public SupplierCompany findById(String id) {
        return supplierCompanyDao.findById(id);
    }

    @Override
    public SupplierCompanyWarpper findWarpperById(String id) {
        SupplierCompany bean = supplierCompanyDao.findById(id);
        if(bean != null){
            SupplierCompanyWarpper warpper = new SupplierCompanyWarpper();
            BeanUtils.copyProperties(bean,warpper);
            String files = bean.getFiles();
            if (StringUtils.isNotBlank(files)) {
                String[] fileIdsArray = files.split(",");
                List fileIds = Arrays.asList(fileIdsArray);
                if(fileIds != null && fileIds.size() != 0) {
                    List fileInfos = fileInfoDao.queryFiles(fileIds);
                    warpper.setFileInfoList(fileInfos);
                }

            }
            return warpper;
        }
        return null;
    }
}
